<?php
$ROOT = "../../../";
require_once ($ROOT . 'config/config.php');
@session_start();

class LoginIndex{	
	private $db;
	private $post;
	private $smarty;
	
	function __construct($db, $post, $smarty){
		$this -> db 	= $db;
		$this -> post 	= $post;
		$this -> smarty = $smarty;
	}
	
	
	function login(){
		$username = $this -> post['username'];
		$password = $this -> post['password'];
		$user= User::login($this -> db,$username,$password);
		if($user instanceof User){
			$_SESSION['Kiliwuser'] = $user -> getId();
			$this -> logged();
		}else{ $this -> display();}
	}
	
	
	function display(){			
		if(isset($_SESSION['Kiliwuser'])){
			 $this -> logged();	
		}else{
			$this -> smarty ->display('../templates/login/index.tpl');	
		}			
	}
	
	function logged(){
		$user = User::getUser($this -> db, $_SESSION['Kiliwuser']);
		$type = $user -> getType();
		
		if($type == 1) $page = 'admin'; else $page = "user";
		
		$this -> smarty ->assign('name',$user -> getName());
		
		$this -> smarty ->display('../templates/login/'.$page.'.tpl');
	}
	
	function logout(){
		session_destroy();
		$this -> display();
	}
	
	function main($db,$smarty,$post){
		$method = $post['method'];
		$index = new LoginIndex($db,$post,$smarty);
		
		switch ($method){
			case 'login':
				$index -> login();		
				break;
				
			case 'logout':
				$index -> logout();
				break;
				
			default:
				$index -> display();
		}
	}
}

LoginIndex::main($db,$smarty,$_POST);

?>